const FileUtils = require('./FileUtils')
const fs = require('fs')
const path = require('path')
const marked = require('marked')
module.exports = {
  getFileTree: function (newPath, isAll) {
    var tree = []
    var pp = FileUtils.getPath(newPath)
    if (fs.existsSync(pp)) {
      var files = fs.readdirSync(pp)
      for (var i = 0; i < files.length; i++) {
        var item = files[i],
          pp1 = path.join(pp, item),
          pp2 = path.join(newPath, item),
          st = fs.statSync(pp1),
          obj = {
            'label': item,
            'href': pp2,
            'expand': false
          }
        if (!isAll && item && item.startsWith(".")) {
          continue;
        }
        if (st.isDirectory()) {
          obj.children = this.getFileTree(pp2, isAll);
          obj.state = 'closed';
          obj.expand = true;
        }
        tree.push(obj)
      }
      tree.sort(function (value1, value2) {
        if (value1.dir != value2.dir) {
          return value2.dir - value1.dir
        } else {
          return value1.text > value2.text ? 1 : -1
        }
      })
    }
    return tree
  },
  getFileContent: function (paths) {
    var fs = require('fs');
    // var fileStr = fs.readFileSync(path);
    var obj = {};
    if (paths) {
      var currentPath = FileUtils.getPath(paths)
      if (fs.existsSync(currentPath)) {
        var encoding = FileUtils.getFileEncoding(currentPath)
        var content = FileUtils.getFileContent(currentPath, encoding)
        var ext = path.extname(currentPath)
        if (ext) {
          ext = ext.substring(1)
        }
        obj.path = paths;
        obj.mtime = FileUtils.getLastModifiedTime(currentPath)
        obj.encoding = encoding
        obj.ext = ext
        obj.content = content
        obj.pp = obj.path.replace(/\\/g, '\\\\')
      }
    }
    // let htmlStr = marked(fileStr.toString());
    return obj;
  }
}
